package com.lib.audioDecoder.player;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

public class PCMPlayer {

    private AudioTrack mAudioTrack = null;
    private boolean isStop = false;

    public PCMPlayer(int bufferSize, int sampleRate, int channel){
        int streamType = AudioManager.STREAM_MUSIC;//音乐类型，扬声器播放

        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;//需要采用和录音时一样采样精度

        int channelConfig = channel == 1?AudioFormat.CHANNEL_OUT_MONO:AudioFormat.CHANNEL_OUT_STEREO;//录音时采用单声道输入，故而播放时也采用单声道播放

        int mode = AudioTrack.MODE_STREAM;//流模式

        int minBufferSize = AudioTrack.getMinBufferSize(sampleRate
                ,channelConfig,audioFormat);

        mAudioTrack = new AudioTrack(streamType,sampleRate,channelConfig
                ,audioFormat,Math.max(bufferSize,minBufferSize),mode);
        mAudioTrack.play();
    }


    public void play(byte[] data,int len){
        if (isStop){
            return;
        }

        int res = mAudioTrack.write(data,0,len);
        switch (res){
            case AudioTrack.ERROR_BAD_VALUE:
            case AudioTrack.ERROR_INVALID_OPERATION:
            case AudioTrack.ERROR_DEAD_OBJECT:
                //TODO:播放失败
                Log.i("MAudioPlayer","播放失败");
            default:
                break;
        }
    }

    public void play(short[] data,int len){
        if (isStop){
            return;
        }

        int res = mAudioTrack.write(data,0,len);
        switch (res){
            case AudioTrack.ERROR_BAD_VALUE:
            case AudioTrack.ERROR_INVALID_OPERATION:
            case AudioTrack.ERROR_DEAD_OBJECT:
                //TODO:播放失败
                Log.i("MAudioPlayer","播放失败");
            default:
                break;
        }
    }


    public synchronized void stop(){
        isStop = true;

        if (mAudioTrack != null){
            mAudioTrack.stop();
            mAudioTrack.release();
            mAudioTrack = null;
        }
    }
}